package com.zengqingfa.basic.classloader;

import org.junit.jupiter.api.Test;

import java.sql.DriverManager;

/**
 *
 * @fileName: ClassLoaderTest2
 * @author: zengqf3
 * @date: 2021-5-10 14:29
 * @description:
 */
public class ClassLoaderTest2 {

    @Test
    public void test() {

    }

    @Test
    public void testGetClassLoader() {
        Class clazz = ClassLoaderTest2.class;
        //方式一：获取当前类的ClassLoader
        ClassLoader classLoader = clazz.getClassLoader();
        //获取当前类的ClassLoader:sun.misc.Launcher$AppClassLoader@18b4aac2
        System.out.println("获取当前类的ClassLoader:" + classLoader);
        //方式二：获取当前线程上下文的ClassLoader
        ClassLoader classLoader1 = Thread.currentThread().getContextClassLoader();
        //获取当前线程上下文的ClassLoadersun.misc.Launcher$AppClassLoader@18b4aac2
        System.out.println("获取当前线程上下文的ClassLoader" + classLoader1);
        //方式三：获取系统的 ClassLoader
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        //系统的 ClassLoader:sun.misc.Launcher$AppClassLoader@18b4aac2
        System.out.println("系统的 ClassLoader:" + systemClassLoader);
    }

    @Test
    public void test3() throws Exception {
        MyClassLoader myClassLoader = new MyClassLoader(ClassLoader.getSystemClassLoader().getParent());
        Class<?> c1 = Class.forName("com.zengqingfa.basic.classloader.User", true, myClassLoader);
        Object obj = c1.newInstance();
        //  User{name='null'}
        System.out.println(obj);
        //com.zengqingfa.basic.classloader.MyClassLoader@13c27452
        System.out.println(obj.getClass().getClassLoader());
    }
}
